//
//  LXImageScrollView.m
//  ProjectSource_Demo
//
//  Created by Liu on 15/11/27.
//  Copyright © 2015年 AngryBear. All rights reserved.
//

#import "LXImageScrollView.h"

const static NSString *kImageViewReuseKey = @"kImageViewReuseKey";

@interface LXImageScrollView ()<UIScrollViewDelegate>

@property (nonatomic, strong) NSMutableDictionary *reuseDictionary;

@end

@implementation LXImageScrollView

- (instancetype)initWithImages:(NSArray *)images
{
    if (self = [super initWithFrame:CGRectZero]) {
        self.imagesArray = images;
        [self reloadImages];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.delegate = self;
        [self reloadImages];
    }
    return self;
}

- (void)reloadImages
{
    CGSize size = self.contentSize;
    size.width = size.width*self.imagesArray.count;
    self.contentSize = size;
}

- (UIImageView *)imageView
{
    UIImageView *imageView = [self.reuseDictionary objectForKey:kImageViewReuseKey];
    if (!imageView) {
        imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        CGFloat r = arc4random()%255;
        CGFloat g = arc4random()%255;
        CGFloat b = arc4random()%255;
        imageView.backgroundColor = RGBAlpha(r, g, b, 1);
    }
    return imageView;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger index = scrollView.contentOffset.y/self.bounds.size.width;
    UIImageView *imageView = (UIImageView *)[self viewWithTag:index];
    if (!imageView) {
        imageView = [self imageView];
    }
    
}

#pragma mark - Property Methods
- (NSMutableDictionary *)reuseDictionary
{
    if (!_reuseDictionary) {
        _reuseDictionary = [NSMutableDictionary dictionary];
    }
    return _reuseDictionary;
}

@end
